package com.unknowpupil.web.component.wallet.scheduled;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.http.HttpService;

import java.io.IOException;
import java.math.BigInteger;

/**
 * @Classname: TransactionWatcherExample
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/10/19 23:08
 * @Description:
 * @Version: 1.0
 */
@Component
public class TransactionWatcherExample {

    private Web3j web3j = Web3j.build(new HttpService("https://mainnet.infura.io/v3/70b25cf11fbb46f4858c3e83b03054f6"));

    //上次轮询到的块高度
    private BigInteger lastBlockNumber;

    /**
     * 扫块监听eth交易，每45秒一次轮询
     * @throws IOException
     */
    @Scheduled(fixedDelay = 45 * 1000)
    public void watchEthTransaction() throws IOException {

        //获取当前块高度
        BigInteger currentBlockNumber = web3j.ethBlockNumber().send().getBlockNumber();

        //运行初始化
        if (lastBlockNumber == null || currentBlockNumber.subtract(lastBlockNumber).compareTo(BigInteger.valueOf(100)) > 0) {
            lastBlockNumber = BigInteger.valueOf(currentBlockNumber.longValue());
            return;
        }

        long futureBlockNum = currentBlockNumber.intValue() + 1;

        //遍历区块
        for (int i = lastBlockNumber.intValue(); i < futureBlockNum; i++) {

            //获取block
            EthBlock.Block block = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(BigInteger.valueOf(i)), true).send().getBlock();

            if (block == null) {
                continue;
            }

            // 遍历block中的交易
            for (EthBlock.TransactionResult tx : block.getTransactions()) {
                if (tx instanceof EthBlock.TransactionObject) {

                    //transaction: 块中的单笔交易
                    EthBlock.TransactionObject transaction = (EthBlock.TransactionObject) tx;


                    // todo 交易判断和处理逻辑


                }
            }
        }

        lastBlockNumber = BigInteger.valueOf(futureBlockNum);

    }

}

